package logbrowse;

import java.awt.Color;
import java.awt.Font;
import java.util.ArrayList;

import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.DefaultHighlighter;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Element;
import javax.swing.text.Highlighter.HighlightPainter;

public class ViewCode extends JTextPane {
	private static final Color COLOR_DEL = new Color(255, 200, 200);
	private static final Color COLOR_INS = new Color(200, 255, 200);
	private static final Color COLOR_MOD = new Color(255, 255, 200);
	private static final DefaultHighlighter.DefaultHighlightPainter HL_DEL
		= new DefaultHighlighter.DefaultHighlightPainter(COLOR_DEL);
	private static final DefaultHighlighter.DefaultHighlightPainter HL_INS
		= new DefaultHighlighter.DefaultHighlightPainter(COLOR_INS);
	private static final DefaultHighlighter.DefaultHighlightPainter HL_MOD
		= new DefaultHighlighter.DefaultHighlightPainter(COLOR_MOD);
	
	private LogEntry entry;
	private LogEntryDiff diff;
	private int diffIndex;
	
	public ViewCode() {
		setFont(new Font("monospaced", Font.PLAIN, 12));
		setEditable(false);
		setDocument(new DefaultStyledDocument());
	}
	
	public void setContents(LogEntry entry, LogEntryDiff diff, int diffIndex) {
		this.entry = entry;
		this.diff = diff;
		this.diffIndex = diffIndex;
		
		if (entry == null) {
			setText("");
		} else {
			setText(entry.getText());
		}
		
		String text = getText();
		ArrayList<Integer> newlines = new ArrayList<Integer>();
		newlines.add(0);
		int pos = text.indexOf('\n');
		while (pos >= 0) {
			newlines.add(pos + 1);
			pos = text.indexOf('\n', pos + 1);
		}
		newlines.add(text.length());

		getHighlighter().removeAllHighlights();
		if (diffIndex == 0) {
			for (Integer line : diff.getDeletions()) {
				colorLine(line, HL_DEL, newlines);
			}
			for (Integer line : diff.getChangesSource()) {
				colorLine(line, HL_MOD, newlines);
			}
		} else {
			for (Integer line : diff.getInsertions()) {
				colorLine(line, HL_INS, newlines);
			}
			for (Integer line : diff.getChangesDest()) {
				colorLine(line, HL_MOD, newlines);
			}
		}
	}
	
	private void colorLine(int line, HighlightPainter highlight, ArrayList<Integer> newlines) {
		int p0 = newlines.get(line);
		int p1 = newlines.get(line + 1);
		try {
			getHighlighter().addHighlight(p0, p1, highlight);
		} catch(BadLocationException e) { }
	}
}
